package com.iiifi.kite.xss.configuration;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.iiifi.kite.xss.core.FormXssClean;
import com.iiifi.kite.xss.core.JacksonXssClean;
import com.iiifi.kite.xss.core.XssCleanInterceptor;
import com.iiifi.kite.xss.propertis.KiteXssProperties;

import lombok.RequiredArgsConstructor;

/**
 * jackson xss 配置
 *
 * @author kite@iiifi.com 花朝
 */
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(KiteXssProperties.class)
@ConditionalOnProperty(value = "kite.xss.enabled", havingValue = "true", matchIfMissing = true)
public class KiteXssConfiguration implements WebMvcConfigurer {
    private final KiteXssProperties xssProperties;

    @Bean
    public FormXssClean formXssClean() {
        return new FormXssClean();
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer xssJacksonCustomizer() {
        return builder -> builder.deserializerByType(String.class, new JacksonXssClean());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        XssCleanInterceptor interceptor = new XssCleanInterceptor(xssProperties);
        registry.addInterceptor(interceptor)
                .addPathPatterns(xssProperties.getPathPatterns())
                .excludePathPatterns(xssProperties.getExcludePatterns())
                .order(Ordered.LOWEST_PRECEDENCE);
    }

}
